<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <script type="text/javascript" src="https://api.map.baidu.com/api?type=webgl&v=1.0&ak=c6OUOAFB3TFHCGDH1Vem5Ngt"></script>
    <title>Sale Map</title>
    <style>
        body,html{
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
        }
        #container{
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        #result{
            position: fixed;
            top: 10px;
            left: 10px;
            width: 350px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            background: #fff;
            box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
            border-radius: 7px;
            z-index: 99;
            display: none;
        }

        #search{
            position: fixed;
            top: 10px;
            left: 10px;
            width: 250px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            background: #fff;
            box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
            border-radius: 7px;
            z-index: 99;
        }
        #search input{
            padding-right: 20px;
            width: 220px;
            touch-action: manipulation;
        }
        #clear-icon {
            position: absolute;
            top: 50%;
            right: 5px;
            transform: translateY(-50%);
            cursor: pointer;
        }


        .marker-info table {
            border-collapse: collapse;
            width: 100%;
        }
        .marker-info th, .marker-info td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .marker-info td {
            width: 320px;
        }
        .marker-info th {
            width: 80px;
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .marker-info tr:hover {
            background-color: #f5f5f5;
        }

        .result button {
            display: inline-block;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            font-size: 16px;
            border: none;
            cursor: pointer;
            border-radius: 4px;
        }

        .result.active button {
            background-color: #f44336;
        }
    </style>
</head>
<body>
<div id='container'></div>
<div id='result'></div>
<div id="search">
    <input id="search-input" type="text" placeholder="设摊人/约摊人/地址/日期"/>
    <span id="clear-icon">&times;</span>
</div>
<script>

    var map = new BMapGL.Map('container');
    let host = new BMapGL.Point(120.311736,30.240291);
    map.centerAndZoom(host, 13);
    map.enableScrollWheelZoom(true);


    var allData=[];
    var uniqueDates = new Set(["all"]);



    function fetchData(url) {
        return fetch(url)
            .then(response => response.json())
            .catch(error => {
                console.error('Error fetching data:', error);
                throw error;
            });
    }
    async function processMultipleData() {
        try {

            const [saleData, unAblePlace, addressPositions] = await Promise.all([
                fetchData('./data/saleData.json'),
                fetchData('./data/unAblePlace.json'),
                fetchData('./data/addressPositions.json')]);

            // 处理数据
            saleData.forEach(function(r) {
                if(!r.date || !r.addr){
                    return;
                }
                let lastIndex = Math.max(r.addr.indexOf('('), r.addr.indexOf('（'));
                if (lastIndex !== -1) {
                    r.addr = r.addr.substring(0, lastIndex);
                }
                r.addr = r.addr.trim()
                let addressPosition = addressPositions[r.addr];
                if (addressPosition == null) {
                    console.warn("no position"+r.addr)
                    return;
                }
                r.lat = addressPosition.lat
                r.lng = addressPosition.lng
                uniqueDates.add(r.date);
                allData.push(r);

            });

            // console.log(uniqueDates);
            // initButtons();
            unAblePlace.forEach(function (r) {
                allData.push(r);
            });
            drawMarkers(allData);

        } catch (error) {
            console.error('Error processing data:', error);
        }
    }

    processMultipleData();





    function fetchUnAbles() {
        fetch('./data/unAblePlace.json')
            .then(response => response.json())
            .then(data => {
                // 在这里可以访问加载的JSON数据，它已经被转换为JavaScript对象

            })
            .catch(error => {
                // 处理加载错误
                console.error('Error:', error);
            });
    }






    var div = document.getElementById("result");


    function initButtons() {
        // 创建按钮组的状态数组
        // 循环遍历状态数组，创建按钮元素并添加到div中
        uniqueDates.forEach(dateItem => {
            // 创建按钮元素
            var button = document.createElement("button");
            button.innerHTML = dateItem;

            // 给按钮添加点击事件监听器
            button.addEventListener("click", function () {
                // 在点击按钮时切换按钮的状态
                filterData(dateItem);
                if (this.classList.contains("active")) {
                    this.classList.remove("active");
                } else {
                    this.classList.add("active");
                }
            });

            // 将按钮添加到div中
            div.appendChild(button);
        });
    }

    function filterData(dateItem) {
        var filteredData = allData;
        if (dateItem !== 'all') {
            filteredData = allData.filter(item => item.date === dateItem);
        }
        drawMarkers(filteredData);
    }
    function searchFilter(keyword) {
        var filteredData = allData;
        if (keyword) {
            filteredData = allData.filter(item => {
                if(keyword.match(/^\d+\/\d+$/)){
                    return item.date&&item.date.endsWith("/"+keyword);
                }
                else{
                    return item.addr.toLowerCase().includes(keyword.trim().toLowerCase())
                        ||(item.saler&&item.saler.toLowerCase().includes(keyword.trim().toLowerCase()));
                }
            });
        }
        drawMarkers(filteredData);
    }


    function drawMarkers(datas) {
        map.clearOverlays();
        var moveToFirstPoint = 0<datas.length && datas.length<4;
        drawHost();
        const groupedData = datas.reduce((acc, obj) => {
            const key = obj.lat +","+obj.lng;
            if (!acc[key]) {
                acc[key] = [];
            }
            acc[key].push(obj);
            return acc;
        }, {});
        Object.keys(groupedData).forEach(function(group) {
            let records = groupedData[group];
            r=records[0]
            let point = new BMapGL.Point(r.lng, r.lat);
            if (moveToFirstPoint){
                map.setCenter(point);
                moveToFirstPoint = false;
            }
            const sold = records.map(r => parseInt(r.sold) || 0).reduce((acc, curr) => acc + curr, 0)
            var markColor =
                r.unAble?"grey"
                :sold<10?"blue"
                :sold<20?"yellow"
                :sold<30?"red"
                :"purple";
            var markerOptions = {
                icon: new BMapGL.Icon('./icons/marker_'+markColor+'.png', new BMapGL.Size(23, 25)),
                offset: new BMapGL.Size(1, -12)
            }
            var marker = new BMapGL.Marker(point,markerOptions);

            var tableContent = '<table class="marker-info" style="display: flex; flex-direction: column;">'
                    // +
                // '<tr>' +
                // '<th><strong>日期:</strong></th>' +
                // '<th><strong>时间:</strong></th>' +
                // '<th><strong>数:</strong></th>' +
                // '</tr>'
            ;
            for (let recordsKey in records) {
                if (!records[recordsKey].date || !records[recordsKey].time) {
                    continue;
                }
                tableContent += '<tr>' +
                '<td>'+records[recordsKey].date+'</td>' +
                '<td>'+records[recordsKey].time.replace(/\s/g, '').replace(/：/g, ':')+'</td>' +
                '<td style="width:30px">'+records[recordsKey].sold+'</td>' +
                '</tr>'
            }


                '</table>';

            if (r.unAble) {
                tableContent = r.reason;
            }

            var infoWindow = new BMapGL.InfoWindow(tableContent, {
                offset: new BMapGL.Size(0, -25), // 将小尾巴位置上移30像素
                width: 300,
                title: r.addr
            });

            function mouseoutHandler() {
                // 在鼠标离开Marker时关闭信息窗口
                map.closeInfoWindow();
            }

            marker.addEventListener("mouseover", function () {
                // 在鼠标悬浮在Marker上时打开信息窗口
                map.openInfoWindow(infoWindow, point);
                marker.addEventListener("mouseout", mouseoutHandler);
            });
    // 给Marker添加鼠标离开事件监听器

            marker.addEventListener("click", function () {
                // 在鼠标单击Marker时打开信息窗口
                map.openInfoWindow(infoWindow, point);
                marker.removeEventListener("mouseout", mouseoutHandler);
            });
    // 创建Label
            if (! r.unAble) {


                let num = records.length+'';
                var label = new BMapGL.Label(num, {
                    offset: new BMapGL.Size(-5 - (num.length / 2) * 8, -27) // 设置Label的偏移量，使其位于Marker的右上方
                });
                // 设置Label的样式
                label.setStyle({
                    color: "#fff",
                    backgroundColor: 'transparent', // 背景颜色设置为透明
                    // backgroundColor: 'rgba(128, 128, 128, 0.1)',
                    border: "none",
                    borderRadius: "50%",
                    padding: "5px",
                    fontSize: "12px",
                    fontWeight: "bold",
                    display: "inline-block"
                });
                // 将Label添加到Marker上
                marker.setLabel(label);
            }
            map.addOverlay(marker);
            //console.log(r);
        });
    }
    function drawHost() {
        var hostMarker = new BMapGL.Marker(host,{
            icon:new BMapGL.Icon('./icons/costco_t.png',new BMapGL.Size(74, 23)),
            offset:new BMapGL.Size(0, -20)
        });
        // hostMarker.setIcon(new BMapGL.Icon("./icons/costco.png", new BMapGL.Size(40, 40))) ;
        // 创建标签对象
        // var label = new BMapGL.Label('Costco', {
        //     offset: new BMapGL.Size(-20, -40) // 设置标签的偏移量
        // });

        // // 设置标签样式
        // label.setStyle({
        //     color: '#f00', // 字体颜色
        //     backgroundColor: 'rgba(255, 255, 255, 0.5)', // 背景颜色设置为透明
        //     border: 'none', // 边框样式
        //     fontWeight: 'bold', // 设置粗体
        //     fontStyle: 'italic', // 设置斜体
        //     textShadow: '5px 5px 5px #fff' // 设置白色描边
        // });
        //
        // // 给标记点添加标签
        // hostMarker.setLabel(label);
        var infoWindow = new BMapGL.InfoWindow("这里是Costco卖场", {
            offset: new BMapGL.Size(0, -25), // 将小尾巴位置上移30像素
            enableAutoPan: true,
            // title: "这里是Costco卖场",
            // height: '40px'
        });
        // infoWindow.setTitle("这里是Costco卖场");

        hostMarker.addEventListener("mouseover", function() {
            // 在鼠标悬浮在Marker上时打开信息窗口
            map.openInfoWindow(infoWindow, host);
        });
        // 给Marker添加鼠标离开事件监听器
        hostMarker.addEventListener("mouseout", function() {
            // 在鼠标离开Marker时关闭信息窗口
            map.closeInfoWindow();
        });
        hostMarker.addEventListener("click", function () {
            // 在鼠标单击Marker时打开信息窗口
            map.openInfoWindow(infoWindow, host);
        });
        hostMarker.setTop(true);
        map.addOverlay(hostMarker);
    }

    var clearIcon = document.getElementById("clear-icon");
    var searchInput = document.getElementById("search-input");

    clearIcon.addEventListener("click", function() {
        searchInput.value = "";
        searchFilter("");
    });
    //搜索事件
    var timeoutId;
    searchInput.addEventListener("input", function() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() {
            // 在这里执行你的事件处理逻辑
            searchFilter(searchInput.value);
            // console.log(searchInput.value);
        }, 500); // 设置延迟时间，单位为毫秒
    });
</script>
</body>
</html>